
`define S0  2'b00 //??
`define S1  2'b01 //??
`define S2  2'b11 //??
`define S3  2'b10 //??
module controller(
    input CLK, RESET, S,
    output reg HG,HY,HR,FG,FY,FR,
    output reg [3:0] TimerH,TimerL
);
 
    wire T1,Ts,Ty;                 
    reg St;                     
    reg [1:0] CurrentState,NextState;//FSM
    always @(posedge CLK, negedge RESET )
    begin:counter
        if (~RESET)  {TimerH, TimerL}=8'b0;
        else if (St) {TimerH, TimerL}=8'b0;
        else if ((TimerH==5) & (TimerL==9))
            begin  {TimerH, TimerL}={TimerH, TimerL}; end
        else if (TimerL==9)
            begin TimerH=TimerH+1; TimerL=0; end
        else
            begin TimerH=TimerH; TimerL=TimerL+1; end
    end
    assign Ty=(TimerH==0)&(TimerL==4);
    assign Ts=(TimerH==2)&(TimerL==9);
    assign T1=(TimerH==5)&(TimerL==9);
  
    //FSM
    always @(posedge CLK, negedge RESET )
    begin:statereg
        if (~RESET)
                CurrentState<='S0;
        else    CurrentState<=NextState;
    end
    //FSM????
    always @(S,CurrentState,T1,Ts,Ty)
    begin: fsm
        case(CurrentState)
        `S0: begin      //S0
            {HG, HY, HR}=3'b100;  
            {FG, FY, FR}=3'b001; 
            NextState=(T1 && S)? `S1:`S0;
            St=(T1 && S)? 1:0;
    end
    `S1:begin
            {HG, HY, HR}=3'b010;  
            {FG, FY, FR}=3'b001;  
           NextState=(Ty)? `S2:`S1;
           St=(Ty)? 1:0;
    end
    `S2:begin
           {HG, HY, HR}=3'b001;  
           {FG, FY, FR}=3'b100;  
           NextState=(Ts ||~S)? `S3:`S2;
           St=(Ts ||~S)? 1:0;
    end
    `S3:begin
              {HG, HY, HR}=3'b001; 
            {FG, FY, FR}=3'b010; 
           NextState=(Ty)? `S0:`S3;
           St=(Ty)? 1:0;
    end
    endcase
end   //fsm
  
    
endmodule
